package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock{
    private final String lockName;
    private final String keyPrefix="lock:";
    private final String uuid = String.valueOf(UUID.randomUUID(true))+"-";
    private StringRedisTemplate stringRedisTemplate;

    public SimpleRedisLock(StringRedisTemplate stringRedisTemplate, String lockName) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.lockName = lockName;
    }
    private final static DefaultRedisScript<Long> UN_LOCK;
    static {
        UN_LOCK = new DefaultRedisScript<>();
        UN_LOCK.setLocation(new ClassPathResource("/lua/unLock.lua"));
        UN_LOCK.setResultType(Long.class);
    }
    @Override
    public boolean tryLock(long timeoutSeconds) {
        //获取线程name
        long threadId = Thread.currentThread().getId();

        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(keyPrefix + lockName, uuid+threadId, timeoutSeconds, TimeUnit.SECONDS);
        //确保不为null
        return Boolean.TRUE.equals(flag);
    }

    @Override
    public void unlock() {
        //判断锁标识
        String key = keyPrefix + lockName;
        String threadId = uuid+Thread.currentThread().getId();
        //改为用lua脚本执行标识判断和删除操作，确保原子性
        stringRedisTemplate.execute(UN_LOCK, Collections.singletonList(key),threadId);
//        String id = stringRedisTemplate.opsForValue().get(key);
//        if (threadId.equals(id)) {
//             stringRedisTemplate.delete(keyPrefix+lockName);
//        }

    }
}
